import os

from PyQt6.QtCore import QFile, QObject
from PyQt6.QtNetwork import QHostAddress

import WebService


class FileServer(QObject):

    def __init__(self):
        super(FileServer, self).__init__()
        # 缓存字节数
        self.payloadsize = 64 * 1024
        self.sendcount = 0

    def sendFile(self, filepath, receiver) -> str | None:
        """
        发送文件
        :param filepath: 文件路径
        :param receiver: 接收者
        :return: 异常信息，成功发送则返回 None
        """


        return None

    def recvFile(self, filepath, size):
        self.filerecv = QFile(filepath)
        self.filesize = size

    def handleFileSend(self):
        """
        通过 TCP 向客户端发送文件的具体方法
        """





    def handleFileRecv(self):
        """
        接收客户端通过 Tcp 发送文件的具体方法
        """
        filepath = self.filerecv
        filesize = self.filesize
        file = QFile(filepath)
        if file.exists():
            file.remove()
        file.open(QFile.OpenModeFlag.WriteOnly)
        while filesize > 0:
            block = WebService.tcpfilesocket.read(self.payloadsize)
            file.write(block)
            filesize -= len(block)
        file.close()
        WebService.tcpfilesocket.abort()
